package com.test.thread;

public class ConsumerDemo {
    public static void main(String[] args) {
        Res res=new Res();
        Thread t0=new Thread(new Producer(res));
        Thread t1=new Thread(new Producer(res));
        Thread t2=new Thread(new Constomer(res));
        Thread t3=new Thread(new Constomer(res));
        t0.start();
        t1.start();
        t2.start();
        t3.start();
    }
}

//描述资源类
class Res {
    private String name;
    private int count;
    private  boolean flag;

    public synchronized void set(String name) {
        while (flag){
        //if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        count++;
        System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name+"--"+this.count);
        flag=true;
        //notify();
        notifyAll();
    }

    public synchronized void get() {
        while (!flag){
        //if(!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "...消费者..." + this.name+"--"+this.count);
        flag=false;
       // notify();
        notifyAll();
    }
}

class Producer implements Runnable {
    private Res res;

    Producer(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true){
            res.set("面包");
        }
    }
}

class Constomer implements Runnable{
    private Res res;
    Constomer(Res res){
        this.res=res;
    }

    @Override
    public void run() {
        while (true) {
            res.get();
        }
    }
}
